package com.emm.yixun.system.service.impl.manage;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.MsgSettingService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.MsgSetting;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.MsgSettingDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.TempTypeEnum;
import com.emm.yixun.common.utils.MsgUtil;

@Service("userCareNoticeManage")
public class UserCareNoticeManage {

	@Autowired
	private MsgSettingService msgSettingService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private UserService userService;
	@Autowired
	private SysNoticeManage sysNoticeManage;
	
	/**
	 * 插入消息
	 * @param reqDto
	 * @return
	 */
	public CommonResDTO createNotice() {
		CommonResDTO resDto = new CommonResDTO();
		resDto.setResult("0");
		try{
			//1、根据sys_tm_msg_setting设置,获取客户关怀提醒时间
			MsgSettingDto settingDto = new MsgSettingDto();
			settingDto.setTempType(TempTypeEnum.RE08.getNo());
			//不同的商户有不同的时间设置
			List<MsgSetting> settingList = msgSettingService.selectListByDto(settingDto);
			if(settingList != null){
				//1、生日当天提醒模板 NT42（当事人）
				String birthCurrTemp_2 = "${userName},生日快乐！";
				//2、生日当天提醒模板 NT43 （销售组所有人【当事人除外】）
				String birthCurrTemp = "今天是${userName}生日,快去问候一下吧！";
				//3、入职周年当天提醒模板 NT44
				String entryTemp_2 = "${userName}，祝你入职${year}周年纪念日快乐！";
				//4、入职周年当天提醒模板 NT45
				//String entryTemp = "${userName}入职${year}周年快乐";
				
				//消息内容模板
				DictionaryDto dicDto = new DictionaryDto();
 				dicDto.setDictionaryType("NT");
 				List<Dictionary> dicList = dictionaryService.selectListByDto(dicDto);
 				if(dicList != null){
 					for(Dictionary dic: dicList){
 	 					if("NT42".equals(dic.getDictionaryValue())){
 	 						birthCurrTemp_2 = dic.getDictionaryName();
 	 					}else if("NT43".equals(dic.getDictionaryValue())){
 	 						birthCurrTemp = dic.getDictionaryName();
 	 					}else if("NT44".equals(dic.getDictionaryValue())){
 	 						entryTemp_2 = dic.getDictionaryName();
 	 					/*}else if("NT45".equals(dic.getDictionaryValue())){
 	 						entryTemp = dic.getDictionaryName();*/
 	 					}
 	 				}
 				}
 				
 				//遍历客户关怀消息设置,查询不同商户的相关客户
 				for(MsgSetting setting: settingList){
 					//获取到商户下所有用户
 					UserDto userAllDto = new UserDto();
 					userAllDto.setMerchantId(setting.getMerchantId());
 					List<User> userAllList = userService.selectListByDto(userAllDto);
 					
 					//当天提醒小时
 					int currHour = setting.getCurrHour();
 					//当天提醒分钟
 					int currMinute = setting.getCurrMinute();
 					//当前日期+触发天数 = 即将过生日的日期
 					Calendar calendar = Calendar.getInstance();
 					int year = calendar.get(Calendar.YEAR);
 					int month = calendar.get(Calendar.MONTH) + 1;
 					int day = calendar.get(Calendar.DAY_OF_MONTH);
 					//获取到商户下所有过生日用户
 					UserDto userDto = new UserDto();
 					userDto.setMerchantId(setting.getMerchantId());
 					userDto.setBirthday(Calendar.getInstance().getTime());
 					List<User> userList = userService.setBirthByDto(userDto);
// 					//2、员工生日在此范围的相关人员
// 					Map<Long, User> userBirthMap = new HashMap<Long, User>();
// 					//3、员工入职周年在此范围的相关人员
// 					Map<Long, User> userEntryMap = new HashMap<Long, User>();
// 					//4、员工入职年限
// 					Map<Long, Integer> entryYearMap = new HashMap<Long, Integer>();
// 					for(User user: userList){
// 						//员工生日
// 						Date userBirth = user.getBirthday();
// 						if(userBirth != null){
// 							Calendar userBirthCalendar = Calendar.getInstance();
// 							userBirthCalendar.setTime(userBirth);
// 							int cusBirthMonth = userBirthCalendar.get(Calendar.MONTH) + 1;
// 							int cusBirthDay = userBirthCalendar.get(Calendar.DAY_OF_MONTH);
// 							if(month == cusBirthMonth && day == cusBirthDay){
// 								userBirthMap.put(user.getId(), user);
// 							}
// 						}
// 						//员工入职周年
// 						Date entryDate = user.getEntryTime();
// 						if(entryDate != null){
// 							Calendar entryCalendar = Calendar.getInstance();
// 							entryCalendar.setTime(entryDate);
// 							int entryYear = entryCalendar.get(Calendar.YEAR);
// 							int entryMonth = entryCalendar.get(Calendar.MONTH) + 1;
// 							int entryDay = entryCalendar.get(Calendar.DAY_OF_MONTH);
// 							if(month == entryMonth && day == entryDay && entryYear != year){
// 								userEntryMap.put(user.getId(), user);
// 								entryYearMap.put(user.getId(), (year-entryYear));
// 							}
// 						}
// 					}
 					
 					Map<String,String> replaceValuesMap=new HashMap<String,String>();
 					//根据获取的客户创建消息
 					//遍历生日相关客户
 					List<User> userEntity = new ArrayList<User>();
 					for(User user1 : userList){
 						userEntity.add(user1);
 						//生日当天通知 - 当事人
 						String sendMsg = birthCurrTemp_2.replace("${userName}", user1.getUserName());
 						System.out.println("1===="+sendMsg);
 						Map<String, String> noticeParamMap = new HashMap<String, String>();
						noticeParamMap.put("noticeDicId", "201");
						noticeParamMap.put("noticeTempType", "NT42");
						noticeParamMap.put("sendMsg", sendMsg);
						noticeParamMap.put("title", "员工关怀,生日当天提醒");
						noticeParamMap.put("timerNotice", year+"-"+month+"-"+day+" "+currHour+":"+currMinute+":10");
						noticeParamMap.put("merchantId", String.valueOf(user1.getMerchantId()));
						noticeParamMap.put("userCode",  user1.getUserCode());
						noticeParamMap.put("accessCode", "system");
						noticeParamMap.put("createUserId", String.valueOf(setting.getCreateUserId()));
						
						/*
						 * 以下代码仅为判断是否已有重复数据（start）
						 * */
						replaceValuesMap.put(MsgUtil.ROOM_ID, "");
						replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
						replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(user1.getId()));
						replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, user1.getUserName());
						replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
						replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
				    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
				    	/*
						 * 以上代码仅为判断是否已有重复数据（end）
						 * */
				    	
				    	//判断是否已有消息
				    	CommonResDTO common1 = sysNoticeManage.isRepeated(noticeParamMap);
				    	if("1".equals(common1.getResult())){
				    		continue;
				    	}
	
		 				sysNoticeManage.createNotice(noticeParamMap, userEntity);
		 				
 					}
 					
 					//根据获取的客户创建消息
 					//遍历生日相关客户
 					for(User user2 : userList){
 						//userEntity.add(user2);
 						//生日当天通知 - 所有人（当事人除外）
 						String sendMsg = birthCurrTemp.replace("${userName}", user2.getUserName());
 						System.out.println("2===="+sendMsg);
 						Map<String, String> noticeParamMap = new HashMap<String, String>();
						noticeParamMap.put("noticeDicId", "202");
						noticeParamMap.put("noticeTempType", "NT43");
						noticeParamMap.put("sendMsg", sendMsg);
						noticeParamMap.put("title", "员工关怀,生日当天提醒");
						noticeParamMap.put("timerNotice", year+"-"+month+"-"+day+" "+currHour+":"+currMinute+":10");
						noticeParamMap.put("merchantId", String.valueOf(user2.getMerchantId()));
						noticeParamMap.put("userCode",  user2.getUserCode());
						noticeParamMap.put("accessCode", "system");
						noticeParamMap.put("createUserId", String.valueOf(setting.getCreateUserId()));
						
						/*
						 * 以下代码仅为判断是否已有重复数据（start）
						 * */
						replaceValuesMap.put(MsgUtil.ROOM_ID, "");
						replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
						replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(user2.getId()));
						replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, user2.getUserName());
						replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
						replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
				    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
				    	/*
						 * 以上代码仅为判断是否已有重复数据（end）
						 * */
				    	
				    	//判断是否已有消息
				    	CommonResDTO common1 = sysNoticeManage.isRepeated(noticeParamMap);
				    	if("1".equals(common1.getResult())){
				    		continue;
				    	}
						
						//发送到商户下除本人外的所有用户
						List<User> allList = new ArrayList<User>();
						for(User user : userAllList){
							if(!user2.getId().equals(user.getId())){
								User newUser = new User();
								BeanUtils.copyProperties(user, newUser);
								allList.add(newUser);
							}
						}
		 				sysNoticeManage.createNotice(noticeParamMap, allList);
		 				
 					}
 					
 					//获取到商户下所有满周年用户
 					UserDto userEntityDto = new UserDto();
 					userEntityDto.setMerchantId(setting.getMerchantId());
 					userEntityDto.setEntryTime(Calendar.getInstance().getTime());
 					List<User> userEntityList = userService.setBirthByDto(userEntityDto);
 					
 					//遍历入职周年相关员工
 					List<User> userEntity_2 = new ArrayList<User>();
 					for(User user3 : userEntityList){
 						userEntity_2.add(user3);
 						//纪念日提前通知 - 当事人
 						Calendar entryCalendar = Calendar.getInstance();
						entryCalendar.setTime(user3.getEntryTime());
 						int entryYear = entryCalendar.get(Calendar.YEAR);
 						String sendMsg = entryTemp_2.replace("${userName}", user3.getUserName())
 								.replace("${year}", (year - entryYear)+"");
 						System.out.println("3===="+sendMsg);
 						Map<String, String> noticeParamMap = new HashMap<String, String>();
						noticeParamMap.put("noticeDicId", "203");
						noticeParamMap.put("noticeTempType", "NT44");
						noticeParamMap.put("sendMsg", sendMsg);
						noticeParamMap.put("title", "员工关怀,入职周年当天提醒");
						noticeParamMap.put("timerNotice", year+"-"+month+"-"+day+" "+currHour+":"+currMinute+":10");
						noticeParamMap.put("merchantId", String.valueOf(user3.getMerchantId()));
						noticeParamMap.put("userCode",  user3.getUserCode());
						noticeParamMap.put("accessCode", "system");
						noticeParamMap.put("createUserId", String.valueOf(setting.getCreateUserId()));
						
						/*
						 * 以下代码仅为判断是否已有重复数据（start）
						 * */
						replaceValuesMap.put(MsgUtil.ROOM_ID, "");
						replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
						replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(user3.getId()));
						replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, user3.getUserName());
						replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
						replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
				    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
				    	/*
						 * 以上代码仅为判断是否已有重复数据（end）
						 * */
				    	
				    	//判断是否已有消息
				    	CommonResDTO common1 = sysNoticeManage.isRepeated(noticeParamMap);
				    	if("1".equals(common1.getResult())){
				    		continue;
				    	}
						
		 				sysNoticeManage.createNotice(noticeParamMap, userEntity_2);
 						
 					}
 					
 					/**
					 * 发送到商户下所有用户
					 * 今后 userList 需改成用户所在用户组所有成员
					 * 需求删除该提醒，需求变更时间2016-07-27
					 */
 					//遍历入职周年相关员工
// 					for(Map.Entry<Long, User> entry: userEntryMap.entrySet()){
// 						User user4 = entry.getValue();
// 						userEntity.add(user4);
// 						//纪念日提前通知 - 所有人（当事人除外）
// 						String sendMsg = entryTemp.replace("${userName}", user4.getUserName())
// 								.replace("${year}", String.valueOf(entryYearMap.get(user4.getId())));
// 						System.out.println("4===="+sendMsg);
// 						Map<String, String> noticeParamMap = new HashMap<String, String>();
//						noticeParamMap.put("noticeDicId", "204");
//						noticeParamMap.put("noticeTempType", "NT45");
//						noticeParamMap.put("sendMsg", sendMsg);
//						noticeParamMap.put("title", "员工关怀,入职周年当天提醒");
//						noticeParamMap.put("timerNotice", year+"-"+month+"-"+day+" "+currHour+":"+currMinute+":10");
//						noticeParamMap.put("merchantId", String.valueOf(user4.getMerchantId()));
//						noticeParamMap.put("userCode", user4.getUserCode());
//						noticeParamMap.put("accessCode", "system");
//						noticeParamMap.put("createUserId", String.valueOf(setting.getCreateUserId()));
//						
////		 				sysNoticeManage.createNotice(noticeParamMap, userEntity);
// 						
// 					}

 				}
			}
			resDto.setResult("1");
		}catch(Exception e){
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("添加提醒消息失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
}
